<?php

require_once('functions/pageLoad.php');
loginRequired();
$user_session = explode("_", $_SESSION['user']);
$user_id = $user_session[0];

if(isset($_GET['token'])){

	$sql = "SELECT payments.id, amount, tradesman.id AS tradesman_id, balance 
	FROM payments 
	LEFT JOIN tradesman ON payments.user_id = tradesman.user_id 
	WHERE payments.user_id = '".$user_id."' AND token = '".mysql_real_escape_string($_GET['token'])."' AND payment_made IS NULL";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);
	$rows = mysql_num_rows($query);

	if($rows == '1'){

	$sql = "UPDATE payments SET payment_made = NOW() WHERE id = '".$rs['id']."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	if(mysql_affected_rows() == '1'){

	$new_balance = $rs['balance'] - $rs['amount'];

	$sql = "UPDATE tradesman SET balance = '".$new_balance."' WHERE id = '".$rs['tradesman_id']."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	$content = '<div class="yellow_box"><p>Thank you for your payment of &pound;'.$rs['amount'].', your balance has been updated.<br /><br /><a href="/my-account"><strong>Return to my account</strong></a></p></div>';

	}

	else{

	$content = '<div class="yellow_box"><p>There was an error processing your request, please try again.</p></div>';

	}

	}

	else{

	$content = '<div class="yellow_box"><p>There was an error processing your request, please try again.</p></div>';

	}
}

else{

	$sql = "SELECT id, balance, username FROM tradesman WHERE user_id = '".$user_id."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$tradesman_rs=mysql_fetch_assoc($query);

	$purchase_token = md5($tradesman_rs['id'].'_'.mktime().'_'.$encryption_salt);

	$sql = "INSERT INTO payments (user_id, tradesman_id, payment_type, amount, ip_address, token) VALUES ('".$user_id."', '".$tradesman_rs['id']."', '1', '".$tradesman_rs['balance']."', '".$_SERVER['REMOTE_ADDR']."', '".$purchase_token."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

$checkout_data = '<?xml version="1.0" encoding="UTF-8"?>
<checkout-shopping-cart xmlns="http://checkout.google.com/schema/2">
  <shopping-cart>
    <items>
      <item>
        <item-name>I Want A Tradesman Outstanding Balance</item-name>
        <item-description>I Want A Tradesman Outstanding Balance</item-description>
        <unit-price currency="GBP">'.$tradesman_rs['balance'].'</unit-price>
        <quantity>1</quantity>
	<digital-content>
	<description>To complete your purchase and clear your balance click the link below.</description>
	<url>http://www.iwantatradesman.co.uk/clear-balance?token='.$purchase_token.'</url>
	</digital-content>
      </item>
    </items>
  </shopping-cart>
  <checkout-flow-support>
    <merchant-checkout-flow-support/>
  </checkout-flow-support>
</checkout-shopping-cart>';

$merchant_id = $settings['google_merchant_id'];
$merchant_key = $settings['google_merchant_key'];
$merchant_encrypt = base64_encode($merchant_id.':'.$merchant_key);

$url = "https://checkout.google.com/api/checkout/v2/merchantCheckout/Merchant/".$merchant_id;

$header_arr = array("Authorization: Basic ".$merchant_encrypt, "Content-Type: application/xml;charset=UTF-8", "Accept: application/xml;charset=UTF-8");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_arr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_POSTFIELDS, $checkout_data);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);

  $objDOM = new DOMDocument();
  $objDOM->loadXML($result);

  $redirect_url_arr = $objDOM->getElementsByTagName("redirect-url");
  $redirect_url = $redirect_url_arr->item(0)->nodeValue;

header("Location: ".$redirect_url);

exit;

}

include('includes/meta.php');
include('includes/header.php');
include('includes/navigation.php');

?>

<h1>Clear balance</h1>

<?php echo $content; ?>

</div>

<?php 

include('includes/rightColumn.php');
include('includes/footer.php');

?>